// 依赖ztree
(function($, undefined) {
    var ie = !!window.ActiveXObject,
        ie6 = ie && !window.XMLHttpRequest;
    $.fn.DataCombo = function(options) {
        return new $.fn.DataCombo.fn.init(options, this);
    };
    $.fn.DataCombo.options = function(options) {
        $.extend(this, options);
    };
    $.fn.DataCombo.options.prototype = {
        key: "id",
        nameKey: "name",
        allowSelectNone: false,
        noneText: "请选择...",
        value: null
    };
    $.fn.DataCombo.fn = $.fn.DataCombo.prototype = {
        init: function(options, view) {
            var options = new $.fn.DataCombo.options(options);
            if (options == undefined) {
                throw "必须指定一个对象参数!"
            }
            if (view == undefined) {
                throw '必须在对象参数中指定view属性!'
            }
            view.addClass("datacomboselect");
            var ow = view.outerWidth();
            this.options = options;
            this.view = view.wrap($("<span class='datacombo'/>")).before("<label>加载中...</label>").parent().outerWidth(ow);
            this.value = options.value != null ? options.value : "";
            this.dataset = new DataSet(options.sqlid);
            this._initView(options);
            this._initDataSet(options);
        },
        _initView: function(options) {
            var that = this;
            this.view.on("click", function() {
                that.show();
            });
            $(window).on("blur", function() {
                that.hide();
            });
        },
        _initDataSet: function(options) {
            var dataset = this.dataset;
            if (options.key != undefined) {
                dataset.key = options.key;
            }
            // 指定参数
            if (options.params != undefined) {
                dataset.params = options.params;
            }
            dataset.afterOpen = $.proxy(function(datas, metadatas) {
                this._render(datas, metadatas);
                this.view.trigger("load");
            }, this);
        },
        _render: function(datas, metadatas) {
            this.drophtml = this._dropdownTemplate($.extend({
                data: this.dataset.datas
            }, this.options, {
                value: this.value
            }));
            this.setValue(this.getValue(), false);
        },
        show: function() {
            var that = this,
                offset,
                toh,
                cssObj;
            if (!that.dropdiv && that.drophtml) {
                that.dropdiv = $(that.drophtml).appendTo("body").on("click", "li", function() {
                    that.setValue($(this).data("value"));
                });
                that.dropdiv.find("[data-value='" + (that.value ? that.value : "") + "']").addClass("selected");
                toh = that.dropdiv.height();
                offset = this.view.offset();
                cssObj = toh + offset.top > $(window).height() + $(document).scrollTop() && offset.top - toh > 0 ? {
                    left: offset.left,
                    bottom: $(window).height() - offset.top - this.view.outerHeight()
                } : {
                    left: offset.left,
                    top: offset.top
                };
                that.dropdiv.css(cssObj).outerWidth(this.view.outerWidth()).find("input").on("click", function(event) {
                    event.stopPropagation();
                }).on("keyup", function(event) {
                    var keyword = $(this).val();
                    if (event.keyCode == 13) {
                        // 回车确认选择第一个
                        that.dropdiv.find("li:visible:first").click();
                    } else {
                        clearTimeout(that._keyupTimeout);
                        that._keyupTimeout = setTimeout(function() {
                            that._search(keyword);
                        }, 250);
                    }
                }).focus();
                setTimeout(function() {
                    $(document).off("click.datacombo").one("click.datacombo", function() {
                        that.hide();
                    });
                    ie6 && $("select").css("visibility", "hidden");
                });
                this.view.find("select").trigger("open");
            }
        },
        hide: function() {
            if (this.dropdiv) {
                this.dropdiv.remove();
                this.dropdiv = null;
                $(document).off("click.datacombo");
                ie6 && $("select").css("visibility", "");
                this.view.find("select").trigger("close");
            }
        },
        _search: function(keyword) {
            var keyword = $.trim(keyword.toLowerCase());
            this.dropdiv.find("li").each(function() {
                var $li = $(this);
                $li[$li.text().toLowerCase().indexOf(keyword) >= 0 ? "show" : "hide"]();
            });
        },
        /* @group 接口 */
        // 事件绑定
        on: function() {
            $.fn.on.apply(this.view, arguments);
        },
        off: function() {
            $.fn.off.apply(this.view, arguments);
        },
        setValue: function(value, trigger) {
            var data = this.dataset.get(value),
                title = data ? data[this.options.nameKey] : this.options.noneText,
                $select;
            this.value = data ? value : null;
            $select = this.view.find("select").html(this._optionsTemplate($.extend({
                data: data
            }, this.options)))
            trigger !== false && $select.trigger("change", [value, data]);
            this.view.find("label").html(title).attr("title", title);
        },
        getValue: function() {
            return this.value;
        },
        // 销毁
        destroy: function() {
            this.dataset.close();
            this.view.off().after(this.view.find("select"));
            this.view.remove();
        },
        // 数据操作
        open: function(options) {
            if (options != undefined) {
                $.extned(this.dataset, options);
            }
            this.dataset.open();
        },
        close: function() {
            this.dataset.close();
        },
        /* @end 接口 */
        _dropdownTemplate: template.compile('<div class="datacombodropdown">\
                <div class="searchbar"><input type="text" placeholder="搜索"/></div>\
                <ul>\
                <% if(allowSelectNone){ %>\
                    <li data-value=""><a><%= noneText %></a></li>\
                <% } %>\
                <% for (var i = 0; i < data.length; i++) {\
                    var item = data[i],\
                        name = item[nameKey],\
                        val = item[key]; %>\
                    <li data-value="<%= val %>"><a href="javascript:;"><%= name %></a></li>\
                <% } %>\
                </ul>\
            </div>'),
        _optionsTemplate: template.compile('<% if(!data){ %>\
                <option selected value=""><%= noneText %></option>\
            <% }else{ \
                var name = data[nameKey],\
                    val = data[key]; %>\
                <option selected value="<%= val %>"><%= name %></option>\
            <% } %>')
    };
    $.fn.DataCombo.fn.init.prototype = $.fn.DataCombo.fn;
})(jQuery);